import {
  request
} from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({
  data: {
    //左侧菜单数据,
    leftMenuList: [],
    rightMenuList: [],
    currentIndex: 0,
    scrollTop: 0
  },
  //接口返回的数据
  Cates: [],
  onLoad: function (options) {
    //从本地缓存中获取数据
    const Cates = wx.getStorageSync('cates')
    //判断
    if (!Cates) {
      //没有数据的时候重新获取
      this.getCates()
    } else {
      //有旧数据的时候还是要判断一下是否是最新的数据，定义过期时间5min
      if (Date.now() - Cates.time > 1000 * 10) {
        //重新发请求
        this.getCates()
      } else {
        this.Cates = Cates.data;
        // 构造左侧的大菜单数据
        const leftMenuList = this.Cates.map(e => e.cat_name)
        // 构造右侧的大菜单数据
        const rightMenuList = this.Cates[0].children
        this.setData({
          leftMenuList,
          rightMenuList
        })
      }
    }
  },
  //获取分类数据
  async getCates() {
    const res = await request({
      url: "/categories"
    })
    this.Cates = res
    wx.setStorageSync('cates', {
      time: Date.now(),
      data: this.Cates
    });
    // 构造左侧的大菜单数据
    const leftMenuList = this.Cates.map(e => e.cat_name)
    // 构造右侧的大菜单数据
    const rightMenuList = this.Cates[0].children
    this.setData({
      leftMenuList,
      rightMenuList
    })
  },
  handleItemTap(e) {
    const {
      index
    } = e.currentTarget.dataset
    const rightMenuList = this.Cates[index].children
    this.setData({
      currentIndex: index,
      rightMenuList,
      scrollTop: 0
    })
  }
});